package com.yueshop.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yueshop.product.service.CategoryBrandRelationService;
import com.yueshop.product.vo.Catelog2Vo;
import org.apache.commons.lang.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yueshop.common.utils.PageUtils;
import com.yueshop.common.utils.Query;

import com.yueshop.product.dao.CategoryDao;
import com.yueshop.product.entity.CategoryEntity;
import com.yueshop.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    //StringRedisTemplate
    //lettuce jedis  操作redis 底层的客户端   RedisTemplate 再次封装


    @Autowired
    RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    //查询三级分类方法
    @Override
    public List<CategoryEntity> listWhithTree() {
        //1.查询所有分类
        List<CategoryEntity> list = this.baseMapper.selectList(null);
        //2.组装父子的树形结构
        //2.1找到所有的一级分类
        List<CategoryEntity> level1Menus = list.stream().filter(CategoryEntity -> {
            return CategoryEntity.getParentCid() == 0;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).map(menu->{
            menu.setChildren(getChildrens(menu,list));
            return menu;
        }).collect(Collectors.toList());

        return level1Menus;
    }

    //通过递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){
        //查询当前分类的 所有子分类
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            //当前root分类id 等于 遍历的 菜单的父id 说明
            return root.getCatId() == categoryEntity.getParentCid();
        }).map(categoryEntity -> {// 子菜单添加 子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;//返回当前菜单
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());//搜集所有数据

        return children;
    }








    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 需要检查当前要删除的菜单,是否被别的地方引用了
        this.baseMapper.deleteBatchIds(asList);
    }
    //找到 catelogPath 的完整 父子孙路径 [2,22,225]
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        //将集合返转  [225,22,2]
        Collections.reverse(parentPath);
        //将list集合转为 Long数组
        return parentPath.toArray(new Long[parentPath.size()]);
    }


    //@Caching(evict = {@CacheEvict(value = {"category"},key = "'getLevel1Catagories'"),@CacheEvict(value = {"category"},key = "'getCatelogJson'")})
    //指定删除分区的数据, allEntries默认是false  设置为true 会删除指定所有分区数据
    @CacheEvict(value = "category",allEntries = true )
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
    //修改category表
        this.updateById(category);
        if(!StringUtils.isEmpty(category.getName())){
            categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
        }
        //修改缓存中的数据
        //redis.del("catelogJson)
    }
    //每一个需要缓存的数据,我们都需要区指定放在那个名字的缓存分区.通常按照业务进行划分
    //key中双引号内容会当作表达式,字符串需要加引号
    @Cacheable(value = {"category"},key = "#root.method.name",sync = true)//表示当前方法需要进行缓存,如果缓存中有数据,方法无需调用,如果缓存中没有,那么会调用这个方法,最后将结果放入缓存
    @Override
    public List<CategoryEntity> getLevel1Catagories() {
        System.out.println("查询了数据库.......");
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;
    }

    private Map<String ,Object> cache  = new HashMap<>();

    /**
     * 空结果缓存:解决缓存穿透
     * 设置过期时间(加随机值):解决缓存雪崩
     * 加锁: 解决缓存击穿
     */
    @Cacheable(value =  {"category"},key = "#root.methodName")
    @Override
    public Map<String, List<Catelog2Vo>> getCatelogJson(){
        System.out.println("重新查询了数据库");
        //查询所有的分类数据
        List<CategoryEntity> selectList = this.baseMapper.selectList(null);
        //1.获取所有一级分类
        List<CategoryEntity> level1Catagories = getParent_cid(selectList, 0L);
        //2.封装数据  key 一级分类id  值
        Map<String, List<Catelog2Vo>> parent_cid = level1Catagories.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //1.根据这个一分类 获取二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
            //2.通过上面的 结果 封装Catelog2Vo
            List<Catelog2Vo> Catelog2Vos = null;
            if (categoryEntities != null) {
                Catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //1.根据当前二级分类 封装三级分类
                    List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());
                    if (level3Catelog != null) {
                        List<Catelog2Vo.Catelog3Vo> collect = level3Catelog.stream().map(l3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return Catelog2Vos;
        }));
        return parent_cid;
    }

    public Map<String, List<Catelog2Vo>> getCatelogJson2() {
        //给缓存中放入json字符串, 拿出json字符串, 转为能够使用的对象[序列化和反序列化]
        //1.获取字符串对象 并通过key  catelogJson 获取redis中保存的数据
        String catelogJson = redisTemplate.opsForValue().get("catelogJson");
        //2.判断字符串是否为空 redis中没有数据库 需要去数据库查询
        if(StringUtils.isEmpty(catelogJson)){
            System.out.println("缓存不命中,查询数据库.....");
            Map<String, List<Catelog2Vo>> jsonFromDb = getCatelogJsonFromDbWithRedissonLock();

            return jsonFromDb;
        }
        System.out.println("缓存命中,直接返回......");
        return JSON.parseObject(catelogJson,new TypeReference<Map<String, List<Catelog2Vo>>>(){});
    }
    public  Map<String, List<Catelog2Vo>> getCatelogJsonFromDbWithRedissonLock() {
        //1.获取锁的名字  11号 商品  proudct-11-lock  proudct-12-lock   proudct-lock
        //锁名字的粒度
        RLock lock = redissonClient.getLock("CatelogJson-lock");
        lock.lock();

        Map<String, List<Catelog2Vo>> dataFromDb;
        try{
            dataFromDb  = getDataFromDb();
        }finally {
            lock.unlock();
        }
        return dataFromDb;
    }

    public  Map<String, List<Catelog2Vo>> getCatelogJsonFromDbWithRedisLock() {
        String uuid = UUID.randomUUID().toString();
        //1.去redis占 用分布式锁
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock",uuid,300,TimeUnit.SECONDS);
        //成功占用分布式锁 返回true 反之 返回fasle
        if(lock){
            System.out.println("获取分布式锁成功..执行业务...");
            //加锁成功 执行业务代码
            Map<String, List<Catelog2Vo>> dataFromDb;
            try{
                dataFromDb  = getDataFromDb();
            }finally {
                //执行完业务.必须执行删除
                //原子化删除 脚本
                String src = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                        "then\n" +
                        "    return redis.call(\"del\",KEYS[1])\n" +
                        "else\n" +
                        "    return 0\n" +
                        "end";
                redisTemplate.execute(new DefaultRedisScript<Long>(src,Long.class),Arrays.asList("lock"),uuid);
            }
            return dataFromDb;
        }else {
            //占锁不成功
            System.out.println("获取分布式锁失败...等待重试");
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCatelogJsonFromDbWithRedisLock();//自旋方式
        }
    }

    private Map<String, List<Catelog2Vo>> getDataFromDb() {
        String catelogJson = redisTemplate.opsForValue().get("catelogJson");
        if (StringUtils.isNotEmpty(catelogJson)) {
            return JSON.parseObject(catelogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
        }
        System.out.println("重新查询了数据库");
        //查询所有的分类数据
        List<CategoryEntity> selectList = this.baseMapper.selectList(null);

        //1.获取所有一级分类
        List<CategoryEntity> level1Catagories = getParent_cid(selectList, 0L);
        //2.封装数据  key 一级分类id  值
        Map<String, List<Catelog2Vo>> parent_cid = level1Catagories.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //1.根据这个一分类 获取二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
            //2.通过上面的 结果 封装Catelog2Vo
            List<Catelog2Vo> Catelog2Vos = null;
            if (categoryEntities != null) {
                Catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //1.根据当前二级分类 封装三级分类
                    List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());
                    if (level3Catelog != null) {
                        List<Catelog2Vo.Catelog3Vo> collect = level3Catelog.stream().map(l3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return Catelog2Vos;
        }));
        //将查询到的数据放入中 将对象转为json字符串
        String jsonString = JSON.toJSONString(parent_cid);
        //放入redis  JSON 好处就是跨语言 跨平台兼容  php
        redisTemplate.opsForValue().set("catelogJson", jsonString, 1, TimeUnit.DAYS);
        return parent_cid;
    }


    public  Map<String, List<Catelog2Vo>> getCatelogJsonFromDb() {

/*        Map<String, List<Catelog2Vo>> catelogJson = (Map<String, List<Catelog2Vo>>) cache.get("catelogJson");
        if(catelogJson==null){
               //调用业务
            //返回数据放入 本地缓存中
            cache.put("catelogJson",parent_cid);
            return parent_cid;
        }
        return  catelogJson;*/
        //只要是同一把锁,就能锁住需要这个锁的所有线程
        //synchronized (this) springboot中 所有的组件再容器中都是单例的


        synchronized (this){
            return getDataFromDb();
        }


    }

    private List<CategoryEntity> getParent_cid( List<CategoryEntity> selectList ,Long parentCid) {
        List<CategoryEntity> collect = selectList.stream().filter(item -> item.getParentCid() == parentCid).collect(Collectors.toList());
        return collect;
    }

    // 递归方法  两个参数  参数1 分类id  收集的 集合
    private List<Long> findParentPath(Long catelogId,List<Long> paths){
        //1.收及当前节点id
        paths.add(catelogId);
        //2.根据当前分类id 获取分类对象
        CategoryEntity entity = this.getById(catelogId);
        //如果当前分类id 不为0 说明 它还有 上级分类,
        if(entity.getParentCid()!=0){
            findParentPath(entity.getParentCid(),paths);
        }
        return  paths;
    }








}